<template>
  <view class="container">
    <view class="container__header">
      <!--   搜索框   -->
      <view class="container__header__search">
        <hxk-search v-model="queryParams.keyword" :currentSearchType.sync="searchType" placeholder="搜索优惠券名称"
                    @search="handleSearch"/>
        <view class="container__header__search-tabs">
          <u-tabs :list="searchTabs" @click="clickSearchTab" keyName="label" :scrollable="false" line-width="80rpx"
                  line-height="16rpx" :line-color="'linear-gradient(to right, #FFA000, #FFFFFF) '"></u-tabs>
        </view>
      </view>
    </view>
    <view class="container__body">
      <!--   列表   -->
      <view class="container__body__list">
        <view class="container__body__list__item" v-for="(item, index) in list" :key="index">
          <view class="container__body__list__item__content">
            <view class="container__body__list__item__content__left"
                  :class="{'active': item.couponRecordState === '1'}">
              <view class="container__body__list__item__content__left__price" v-if="item.couponType === '3'">
                <text>{{ item.couponDenomination }}</text>折
              </view>
              <view class="container__body__list__item__content__left__price" v-else>
                ¥
                <text>{{ item.couponDenomination }}</text>
              </view>
              <view class="container__body__list__item__content__left__condition">
                <text v-if="item.couponType === '1'||item.couponType === '3'">满{{ item.couponThreshold }}可用</text>
                <text v-else-if="item.couponType === '2'">无门槛</text>
              </view>
            </view>
            <view class="container__body__list__item__content__center">
              <view class="container__body__list__item__content__center__name">
                <text>{{ item.couponName }}</text>
              </view>
              <view class="container__body__list__item__content__center__validTime">
                有效期：
                <text>{{ item.activityStartTime }}至{{ item.activityEndTime }}</text>
              </view>
              <view class="container__body__list__item__content__center__desc">
                <view class="container__body__list__item__content__center__desc__label">使用说明：</view>
                <view class="container__body__list__item__content__center__desc__text"
                      v-html="item.couponInstruction"></view>
                <view class="container__body__list__item__content__center__desc__detail"
                      @click="handleShowCouponInstruction(item)">详情
                </view>
              </view>
            </view>
            <view class="container__body__list__item__content__right">
              <view class="container__body__list__item__content__right__button" @click.stop="handleToUseCoupon(item)"
                    :class="{'active': item.couponRecordState === '1'}" v-if="item.couponRecordState === '1'">
                立即使用
              </view>
              <view class="container__body__list__item__content__right__button" v-else>
                {{ item.couponRecordState === '2' ? '已使用' : '已过期' }}
              </view>
            </view>
          </view>
        </view>
        <uni-load-more :status="loadStatus" :contentText="contentText"></uni-load-more>
      </view>
    </view>
    <!--   底部操作栏   -->
    <view class="container__footer">
      <view class="container__footer__button">
        <button @click="handleVerification">卡券核销</button>
      </view>
      <view class="container__footer__button active">
        <button @click="handleToCouponCenter">前往领券中心 >></button>
      </view>
    </view>
    <!--   使用说明弹窗   -->
    <hxk-dialog ref="couponInstructionDialog">
      <view class="dialog__content" slot="content">
        <view class="dialog__content__desc" v-html="dialogData.couponInstruction"></view>
      </view>
    </hxk-dialog>
    <!--   核销弹窗   -->
    <hxk-dialog ref="verificationDialog">
      <view class="verificationDialog__content" slot="content">
        <u-form
            labelPosition="left"
            :model="verificationForm"
            ref="verificationForm"
            :rules="verificationRules"
        >
          <u-form-item label="卡券编号" prop="verificationCode" labelWidth="140rpx">
            <u-input v-model="verificationForm.verificationCode" placeholder="请输入核销码" maxlength="32" type="text"></u-input>
          </u-form-item>
        </u-form>
      </view>
      <view slot="footer" class="verificationDialog__footer">
        <button class="verificationDialog__footer__button" @click.stop="handleVerificationConfirm">核销</button>
      </view>
    </hxk-dialog>
  </view>
</template>
<script>
import {countCouponRecordState, getCouponRecordList, verificationCouponRecord} from "@/api/mine/coupon";
import {debounce} from "@/utils/common";

export default {
  name: "index",
  components: {
  },
  data() {
    return {
      searchType: 'premisesAddress',
      // 搜索标签
      searchTabs: [
        {
          label: "未使用(0)",
          value: "1"
        },
        {
          label: "已使用(0)",
          value: "2"
        },
        {
          label: "已过期(0)",
          value: "3"
        }
      ],
      // 列表数据
      list: [],
      // 总数
      total: 0,
      // 分页参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponRecordState: null,//优惠券使用状态
        keyword: null//搜索关键字
      },
      // 加载状态
      loadStatus: 'more',//more:加载更多,noMore:没有更多数据,loading:加载中
      // 加载提示语
      contentText: {contentdown: '下拉加载更多', contentrefresh: "加载中...", contentnomore: "没有更多数据了"},
      // 弹窗数据
      dialogData: {},
      // 核销弹窗数据
      verificationForm: {
        verificationCode: ''
      },
      // 核销弹窗规则
      verificationRules: {
        verificationCode: [
          {required: true, message: '请输入核销码', trigger: 'blur'}
        ]
      }
    }
  },
  onLoad() {
    // 页面显示,重新获取数据
    this.initData();
    this.getCouponRecordStateCount();

  },
  onReachBottom() {
    // 加载更多,如果总数大于当前页数*pageSize,则加载更多
    if (this.total > this.queryParams.pageNum * this.queryParams.pageSize) {
      this.loadStatus = 'loading';
      this.queryParams.pageNum++;
      this.getList();

    } else if (this.total <= this.queryParams.pageNum * this.queryParams.pageSize) {
      // 已经加载完毕
      console.log("已经加载完毕")
      this.loadStatus = 'noMore';
    }

  },
  methods: {
    initData() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        couponRecordState: '1',//优惠券使用状态
        keyword: ''//搜索关键字
      }
      this.list = [];
      this.total = 0;
      this.getList();
    },
    // 搜索
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.queryParams.keyword = this.queryParams.keyword.trim();
      this.list = [];
      this.getList();
    },
    // 获取列表数据
    getList() {
      this.loadStatus = 'loading';
      setTimeout(() => {
        let params = Object.assign({}, this.queryParams)
        console.log('请求参数', params, this.searchType)
        params[this.searchType] = this.queryParams.keyword
        getCouponRecordList(params).then(res => {
          //当前为第一页
          if (this.queryParams.pageNum === 1) {
            this.list = res.rows;
          } else {
            // 不是第一页,则追加数据
            this.list = this.list.concat(res.rows);
          }
          this.total = res.total;
          this.loadStatus = this.total <= this.queryParams.pageNum * this.queryParams.pageSize ? 'noMore' : 'more';
          // 如果没有数据
          if (this.total === 0) {
            this.loadStatus = 'noMore';
            this.contentText.contentnomore = "暂无数据";
          }
        }).catch(err => {
          console.log(err)
        })

      }, 500);

    },
    // 点击搜索标签
    clickSearchTab(tab) {
      console.log(tab)
      this.queryParams.couponRecordState = tab.value;
      this.handleSearch();
    },
    // 详情
    handleDetail(item) {
      this.$tab.navigateTo('./detail?housePictureId=' + item.housePictureId)
    },
    // 获取状态数量
    getCouponRecordStateCount() {
      countCouponRecordState().then(res => {
        let list = res.data.sort((a, b) => a.couponRecordState - b.couponRecordState);
        this.searchTabs = [
          {
            label: "未使用(" + list[0].num + ")",
            value: "1"
          },
          {
            label: "已使用(" + list[1].num + ")",
            value: "2"
          },
          {
            label: "已过期(" + list[2].num + ")",
            value: "3"
          }
        ];
      })
    },
    // 显示使用说明
    handleShowCouponInstruction(item) {
      this.dialogData = item;
      this.$refs.couponInstructionDialog.confirm({
        title: '使用说明',
        showCancel: false,
        confirmText: '知道了'
      })
    },

    // 立即使用优惠券
    handleToUseCoupon(item) {
      if (['1', '3'].includes(item.applyScope)) {
        this.$tab.switchTab('/pages/home/index')
      } else if (item.applyScope === '2') {
        this.$tab.navigateTo({
          url: '/pages/mine/coupon/activity?coupon=' + JSON.stringify(item),
        })
      }
    },
    // 核销优惠券
    handleVerification() {
      this.verificationForm.verificationCode = '';
      this.$refs.verificationDialog.confirm({
        title: '卡券核销',
        position: 'bottom',
      })
      this.$nextTick(() => {
        this.$refs.verificationForm.setRules(this.verificationRules)
      })
    },
    // 核销确认
    handleVerificationConfirm: debounce(function () {
      this.$refs.verificationForm.validate().then(valid => {
        if (!valid) return
        let params = {
          verificationCode: this.verificationForm.verificationCode
        }
        verificationCouponRecord(params).then(res => {
          this.$modal.msg(res.msg || '核销成功')
          this.initData();
          this.$refs.verificationDialog.hide();
        }).catch(err => {
        })
      }).catch(err => {
        console.log('eer', err)
        this.$modal.msg(err[0].message)
      })
      // if (this.verificationForm.verificationCode.trim() === '') {
      //   this.$modal.msg('请输入核销码')
      //   return
      // }
    }, 500, true),
    // 前往领券中心
    handleToCouponCenter() {
      this.$tab.navigateTo({
        url: '/pages/mine/coupon/coupon-center',
        events: {
          couponCenterCallback: (result) => {
            this.initData();
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  .container__header {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: #fff;
    //height: 154rpx;
    display: flex;
    flex-direction: column;

    .container__header__search {

      .container__header__search-input {
        padding: 0 20rpx;

        .search-btn {
          background: $hxk-primary-color;
          color: #fff;
        }

        .cancel-btn {
          color: $hxk-primary-color;
          background: #fff;
          border: none;

          &:after {
            border: none;
          }
        }

        .container__header__search-input-type {
          margin-top: 10rpx;

          ::v-deep .checklist-group {
            display: flex;
          }

          ::v-deep .is--tag {

            &.is-checked {
              background: $hxk-primary-color !important;
              border-color: $hxk-primary-color !important;
            }
          }
        }
      }

      .container__header__search-tabs {
        ::v-deep .u-tabs__wrapper__nav__item__text {
          font-size: 28rpx !important;
        }

        ::v-deep .u-tabs__wrapper__nav__line {
          bottom: 18rpx !important;
          opacity: 0.6 !important;
        }
      }
    }


  }

  .container__body {
    padding: 20rpx;

    .container__body__list {
      margin-bottom: 150rpx;

      .container__body__list__item {
        background-color: #fff;
        border-radius: 10rpx;
        margin-bottom: 10rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .container__body__list__item__content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20rpx;

          .container__body__list__item__content__left {
            width: 25%;
            text-align: center;

            &.active {
              color: $hxk-primary-color;
            }

            .container__body__list__item__content__left__price {
              font-size: 20rpx;
              margin-bottom: 10rpx;

              text {
                font-size: 32rpx;
                font-weight: bold;
              }
            }

            .container__body__list__item__content__left__condition {
              font-size: 20rpx;
            }
          }

          .container__body__list__item__content__center {
            padding: 0 10rpx;
            border-left: 1rpx dashed #D7D7D7;
            width: 60%;

            .container__body__list__item__content__center__name {
              font-size: 28rpx;
              margin-bottom: 20rpx;
              font-weight: bold;
            }

            .container__body__list__item__content__center__validTime {
              font-size: 24rpx;
              margin-bottom: 20rpx;
            }

            .container__body__list__item__content__center__desc {
              font-size: 24rpx;
              line-height: 32rpx;
              text-align: justify;
              display: flex;

              .container__body__list__item__content__center__desc__label {
                white-space: nowrap;
              }

              .container__body__list__item__content__center__desc__text {
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 1;
                overflow: hidden;
              }

              .container__body__list__item__content__center__desc__detail {
                color: #02BAF6;
                white-space: nowrap;
              }

            }
          }

          .container__body__list__item__content__right {
            width: 15%;
            text-align: center;

            .container__body__list__item__content__right__button {
              display: block;
              width: 100%;
              height: 50rpx;
              line-height: 50rpx;
              border-radius: 10rpx;
              background-color: #ffffff;
              border: 1rpx solid #AAAAAA;
              color: #AAAAAA;
              font-size: 22rpx;

              &.active {
                border: 1rpx solid $hxk-primary-color;
                color: $hxk-primary-color;
              }
            }
          }
        }

      }
    }
  }

  .container__footer {
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: center;
    /* align-items: center; */
    width: 100%;
    padding: 0 20rpx;
    height: 140rpx;
    background: #fff;

    .container__footer__button {
      width: 100%;
      margin-right: 20rpx;

      &:last-child {
        margin-right: 0;
      }

      &.active {
        button {
          background-color: $hxk-primary-color;
          color: #fff;
        }
      }

      button {
        height: 70rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        //background-color: $hxk-primary-color;
        color: #000;
        font-size: 28rpx;
      }

    }
  }
}

.verificationDialog__footer {
  .verificationDialog__footer__button {
    height: 73rpx;
    border-radius: 12rpx 12rpx 12rpx 12rpx;
    font-size: 30rpx;
    color: #fff;
    background-color: #FF7950;
  }
}

</style>
